import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入登录和注册组件
import Login from '@/views/login'
// import Login from '@/views/login/login1.vue'
import Reg from '@/views/reg'

// 导入用户中心组件
import Layout from '@/views/layout'

// 导入首页组件
import Home from '@/views/home'

// 导入基本资料组件
import userInfo from '@/views/user/userInfo.vue'

// 导入vuex实例,调取token
import store from '@/store'

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  // 登录页面
  {
    path: '/login',
    component: Login
  },
  // 注册页面
  {
    path: '/reg',
    component: Reg
  },
  // 后台页面
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    // 子组件
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/user-info',
        component: userInfo
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置守卫
router.beforeEach((to, from, next) => {
  const vips = ['/reg', '/login']
  if (vips.includes(to.path)) {
    next()
  } else {
    if (store.state.user.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
